#pragma once
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <functional>
#include "Log.hpp"
#include "Common.hpp"
#include "IntAddr.hpp"

namespace MySocket
{
    const int gblcklog = 5;

    using namespace MyLog;
    class Socket
    {
    public:
        Socket()
        {
        }
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t port) = 0;
        virtual void ListenOrDie(size_t backlog) = 0;
        virtual std::shared_ptr<Socket> Accept(InetAddr *client) = 0;
        virtual void Close() = 0;
        
        ~Socket()
        {
        }

        void BuildSocket(uint16_t port,size_t backlog = gblcklog)
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie(backlog);
        }
    };

    const int defaultfd = -1;

    class TcpSocket : public Socket
    {
    public:
        TcpSocket() : _listensockfd(defaultfd)
        {
        }
        TcpSocket(int fd) : _listensockfd(fd)
        {
        }
        void SocketOrDie() override
        {
            _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensockfd < 0)
            {
                LOG(Loglevel::ERROR) << "socket error";
                exit(SOCKET_ERROR);
            }
            LOG(Loglevel::ERROR) << "socket success";
        }
        void BindOrDie(uint16_t port) override
        {
            InetAddr addr(port);
            int n = bind(_listensockfd, addr.GetNetAddr(), addr.GetSocklen());
            if (n < 0)
            {
                LOG(Loglevel::ERROR) << "bind error";
                exit(BIND_ERROR);
            }
            LOG(Loglevel::ERROR) << "bind success";
        }
        void ListenOrDie(size_t backlog) override
        {
            int n = listen(_listensockfd, backlog);
            if (n < 0)
            {
                LOG(Loglevel::ERROR) << "listen error";
                exit(LISTEN_ERROR);
            }
            LOG(Loglevel::ERROR) << "listen success";
        }
        //                             输出型参数
        std::shared_ptr<Socket> Accept(InetAddr *client) override
        {
            sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int fd = ::accept(_listensockfd, CONV(&peer), &len);
            if (fd < 0)
            {
                LOG(Loglevel::ERROR) << "accept error";
                exit(ACCEPT_ERROR);
            }
            LOG(Loglevel::ERROR) << "accept success";

            client->SetAddr(peer);
            return std::make_shared<TcpSocket>(fd);
        }

        void Close() override
        {
            if(_listensockfd>0)
                close(_listensockfd);
        }
        ~TcpSocket()
        {
        }

    private:
        int _listensockfd;
    };
}